package com.desksoft.ecommerce.util.html.element.variable;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.utility.StringUtil;

/**
 * 变量集合
 * @author Administrator
 *
 */
public class VariableCollection implements Serializable {

	public Map<String,Variable> varList = new HashMap<String,Variable>();
	
	public void addVariable(Variable var){
		varList.put(var.getType(), var);
	}
	
	/**
	 * 取值，若无匹配变量类型则直接返回key
	 */
	public String getValue(String key){
		
		if (key == null){return "";}
		int index_$ = key.indexOf("$") , index_left = key.indexOf("{"), index_right = key.indexOf("}");
		
		if (index_$ >= 0 && index_left > index_$ && index_right > index_left ){
			String type = key.substring(index_$ + 1 , index_left);
			Variable var = varList.get(type);
			if (var != null){return var.getValue(key);}
		}
		
		return key;
	}
	
	/**
	 * 替换字符串中的变量
	 */
	public String replaceSql(String str){
		String  sql_tmp = str;
		for (int i = 0 ; i < sql_tmp.length() ; i++){
			if (sql_tmp.charAt(i) == '$'){
				int s = i;
				while (sql_tmp.charAt(i) != '}')i++;
				String key = sql_tmp.substring(s, i+1);
				String val = this.getValue(key);
				str = StringUtil.replace(str, key, val, true, false);
			}
		}
		return str;
	}
	
}
